<script setup lang='ts'>
import { ref } from 'vue';
import {
    cancelDetails, commit,
    getCounselors,
    getDetails,
    getSchedule, getStuList,
    searchCoundelors,
    updateSchedulesAll
} from '@/api/axios/orderAxios';
import { formatDate } from '@vueuse/core';
import { parseTime } from '@/utils/ruoyi';
import moment from 'moment';

// 咨询师选择
const counselorsSelect = ref('');
// 咨询师列表
const counselors = ref([]);
getCounselors().then(res => {
    // console.log(res.rows);
    counselors.value = res.rows;
});

const dialogVisible = ref(false);

// 日历
const dataValue = ref(new Date());

const schedule = ref({
    date: formatDate(dataValue.value, 'YYYY-MM-DD'),
    teacherId: ''
});

// 初始化时间表
const calendarData = ref([]);
const calendarDetail = ref([]);

const teacherId = ref('')
function initSchedule() {
    if (schedule.value.teacherId === '') {
        schedule.value.teacherId = '483439052792664064';
        counselorsSelect.value = '陈依云';
    }
    // console.log(schedule.value);
    getSchedule(schedule.value).then(res => {
        console.log(res.rows);
        calendarData.value = res.data;
        calendarDetail.value = res.rows;
    });
}

initSchedule();

function changeCounselor() {
    counselors.value.map(item => {
        if (item.nickName === counselorsSelect.value) {
            schedule.value.teacherId = item.teacherId;
            teacherId.value = item.teacherId
        }
    });
    initSchedule();
}


// 点击日期
function handleDate(data) {
    checkBoxVisible.value = '';
    // dataValue.value=new Date(data.day)
    schedule.value.date =data.day;
    initSchedule();
}

// 可约不可约状态改变
function changeColor(data) {
    let obj = {
        haveTime: null,
        noTime: null
    };
    calendarData.value.map(item => {
        if (item.date === data.day) {
            if (item.status === true) {
                obj.haveTime = true;
                obj.noTime = false;
            } else {
                obj.haveTime = false;
                obj.noTime = true;
            }
        }
    });
    return obj;
}

// 更新排期
const checkBoxVisible = ref('');
const updateOnline = ref('');

function online() {
    checkBoxVisible.value = '2';
}

function rest() {
    checkBoxVisible.value = '0';
}
function cancel() {
    checkBoxVisible.value = '';
}

const updaData = ref({
    id: null, // * 排班id
    status: ''
});

function save() {
    // 保存这里面选中的数据
    console.log(calendarDetail);
    let status;
    if (checkBoxVisible.value === '2') {
        status = 0;
    } else {
        status = 2;
    }
    const ids = calendarDetail.value.filter(item => item.updateOnline).map(item => item.id).join(',');
    updateSchedulesAll({
        ids: ids,
        status
    }).then(res => {
        checkBoxVisible.value = '';
        calendarDetail.value.forEach(item => item.updateOnline = false);
        console.log(res);
        initSchedule();
    });
}

// 点击已约详情
const details = ref({})

const  cancelContent = ref({
    reason: '',
    id: ''
})
function checkDetail(data) {
    if (data.status === '1') {
        dialogVisible.value = true;
        console.log(data);
        getDetails(data.id).then(res => {
            // console.log(res);
            details.value = res.data
            cancelContent.value.id = res.data.id
        })
    }
}

// 取消预约
const cancelVisible = ref(false)

function cancelDetail() {
    dialogVisible.value = false
    cancelVisible.value = true
}
function saveCancel() {
    cancelDetails(cancelContent.value).then(res => {
        console.log(res);
        initSchedule()
    })
    cancelVisible.value = false
}

const menuVisible = ref(false)

const getClassByStatus = (item) => {
    if (item.status === '0') {
        // 如果是开始时间过去了，就变成禁用状态
        // const startDateTime = parseTime()
        let classList = ['tag', 'tagGreen']
        if (moment().diff(item.date+" "+item.startTime) > 0) {
            // 已经过去了
            classList.push("tagGrey")
        }
        return classList;
    } else if (item.status === '1') {
        return 'tag tagRed';
    } else if (item.status === '2') {
        return 'tag tagOrange';
    } else {
        return '';
    }
};

// 右键事件

const status = ref({
    ids: "",
    status: ""
})

const consultation = ref({
    schedulingId: "",
    mode: "线下咨询",
    studentId: "",
    peopleType: null
})


const xData = ref('');
const yData = ref('');
const schedulingId = ref('')
const openMenu = (data) => {
    console.log(data);
    const e = event || window.event;
    if (data.status !== '1') {
        if (moment().diff(data.date+" "+data.startTime) < 0) {

            schedulingId.value = data.id
            status.value.ids = data.id
            if(data.status === '2') {
                status.value.status = '0'
            } else {
                status.value.status = '2'
            }

            // 时间未过去
            menuVisible.value = true
            xData.value = e.clientX + 'px';
            yData.value = e.clientY + 'px';
        }
    }
}

// 状态变更
function updateStatus() {
    menuVisible.value = false
    updateSchedulesAll(status.value).then(res => {
        // console.log(res);
        initSchedule()
    })
}

// 学生预约


const stuVisible = ref(false)
const students = ref([])
function appointStu() {
    stuName.value = ''
    consultation.value = {
        schedulingId: "",
        mode: "线下咨询",
        studentId: "",
        peopleType: null
    }
    stuVisible.value = true
    menuVisible.value = false
    getStuList({teacherId:schedule.value.teacherId}).then(res => {
        console.log(res);
        students.value = res.data
    })
}
// 确定预约
const stuName = ref('')
function saveAppoint() {
    students.value.map(item => {
        if (stuName.value === item.name) {
            consultation.value.studentId = item.id
        }
    })
    if (consultation.value.peopleType === '个人预约') {
        consultation.value.peopleType = 0
    }else {
        consultation.value.peopleType = 1
    }
    consultation.value.schedulingId = schedulingId.value
    console.log(consultation.value);
    commit(consultation.value).then(res => {
        console.log(res);
        initSchedule()
    })
    stuVisible.value = false
}

// 上一天
function lastDay() {
    dataValue.value =new Date( dataValue.value.getTime()- 3600 * 1000 * 24);
    schedule.value.date =  formatDate(dataValue.value, 'YYYY-MM-DD')
    initSchedule()
}
// 下一天
function nextDay() {
    dataValue.value =new Date( dataValue.value.getTime()+ 3600 * 1000 * 24);
    schedule.value.date =  formatDate(dataValue.value, 'YYYY-MM-DD')
    initSchedule()
}

</script>

<template>
    <div class='dateMain'>
        <div class='flex flex-wrap gap-4 items-center'>
            <span>当前咨询师:</span>
            <el-select
                v-model='counselorsSelect'
                placeholder='请选择咨询师'
                size='large'
                style='width: 240px'
                @change='changeCounselor'

                v-hasPermischedulingId="['select']"

            >
                <el-option
                    v-for='item in counselors'
                    :key='item.userId'
                    :label='item.nickName'
                    :value='item.nickName'
                />
            </el-select>
        </div>

        <div class='dateContent'>
            <div>
                <!--               日历-->
                <el-calendar v-model='dataValue' class='calendar'>

                    <template
                        #date-cell='{data}'
                    >
                        <div @click='handleDate(data)' :class='changeColor(data)'>
                            {{ data?.day.split('-').slice(2).join('-') }}
                        </div>
                    </template>
                </el-calendar>
            </div>

            <!--           右侧详情 -->
            <div class='scheduling'>
                <div class='scheduling-header'>
                    <span>详细情况</span>
                    <el-icon>
                        <QuestionFilled />
                    </el-icon>
                    <el-button size='small' style='margin-left: 380px;' @click='lastDay'>上一天</el-button>
                    <el-button size='small' style='margin-left: -1px;' @click='nextDay'>下一天</el-button>
                </div>
                <div class='scheduling-body'>
                    <el-button class='orderBtn' @click='online'>可约</el-button>
                    <el-button class='orderBtn' @click='rest'>休息</el-button>
                    <div style='display: flex;flex-wrap: wrap'>
                        <div style='position: relative' v-for='item in calendarDetail' :key='item.id'
                             :class='getClassByStatus(item)'
                             @click='checkDetail(item)' @contextmenu.prevent='openMenu(item)'
                        >
                            <span> {{ item.startTime }} - {{ item.endTime }} </span>
                            <div class='smallTag smallGreenTag' v-if='item.status === "0"'>可约</div>
                            <div class='smallTag smallRedTag' v-else-if='item.status === "1"'>已约</div>
                            <div class='smallTag smallOrangeTag' v-else>休息</div>
                            <input type='checkbox' v-model='item.updateOnline'
                                   style='position: absolute;left: 0;top: 0' v-show='item.status === checkBoxVisible'>
                        </div>
                        <div v-show='menuVisible' style='height: 100vh;width: 100vw;position: fixed;left: 0;top: 0;z-index: 9999' @click='menuVisible=false'></div>
                        <div class='contextMenu' v-show='menuVisible' :style="{'--x':xData,'--y':yData}" @blur='menuVisible = false'>
                            <div style='margin-bottom: 15px' @click='updateStatus'>
                                <el-icon style='vertical-align: text-top' ><Operation /></el-icon>
                                状态变更
                            </div>
                            <div @click='appointStu'>
                                <el-icon><User style='vertical-align: text-top'/></el-icon>
                                预约学生
                            </div>
                        </div>
                    </div>
                </div>

                <div style='width: 85%;text-align: right'>
                    <el-button @click='cancel'>取消</el-button>
                    <el-button type='primary' @click='save'>保存</el-button>
                </div>

            </div>
            <div style='clear:both'></div>
        </div>
    </div>

    <div>
        <el-dialog
            v-model='dialogVisible'
            title='预约详情'
            width='820'
        >
            <table width='100%' class='stuTable'>
                <tr>
                    <td class='grey'>姓名</td>
                    <td class='content'>{{details.psyStudent?.name}}</td>
                    <td class='grey'>学历</td>
                    <td class='content'>{{details.psyStudent?.education}}</td>
                </tr>
                <tr>
                    <td class='grey'>生日</td>
                    <td class='content'>{{details.psyStudent?.birthday}}</td>
                    <td class='grey'>班级</td>
                    <td class='content'>{{details.psyStudent?.className}}</td>
                </tr>
                <tr>
                    <td class='grey'>学号</td>
                    <td class='content'>{{details.psyStudent?.stuNum}}</td>
                    <td class='grey'>咨询方式</td>
                    <td class='content'>{{details?.mode}}</td>
                </tr>
                <tr>
                    <td class='grey'>问题描述</td>
                    <td class='content' colspan='3'>{{details?.content}}</td>
                </tr>
            </table>
            <template #footer>
                <div class='dialog-footer'>
                    <el-button size='large' @click='cancelDetail'>取消预约</el-button>
                    <el-button type='primary' @click='dialogVisible = false' size='large'>
                        确认
                    </el-button>
                </div>
            </template>
        </el-dialog>
    </div>

    <el-dialog
        v-model="cancelVisible"
        title="取消预约"
        width="450"
    >
        <div>
            <el-input
                v-model="cancelContent.reason"
                style="width: 100%"
                maxlength="200"
                rows='7'
                placeholder="请填写取消预约详情"
                show-word-limit
                type="textarea"
                resize='none'
            />
        </div>
        <template #footer >
            <div class="dialog-footer" style='margin-top: -15px'>
                <el-button @click="cancelVisible = false" >取消</el-button>
                <el-button type="primary" @click="saveCancel">
                    保存
                </el-button>
            </div>
        </template>
    </el-dialog>

    <el-dialog
        v-model="stuVisible"
        title="添加预约"
        width="260"
    >
        <div>
            <p style='font-size:14px;margin:0 0 15px'>选择学生:</p>
            <el-select v-model="stuName" placeholder="请选择" style="width: 100%">
                <el-option
                    v-for="item in students"
                    :key="item.id"
                    :label="item.name"
                    :value="item.name"
                />
            </el-select>
            <p style='font-size:14px;margin: 15px 0'>咨询类型:</p>
            <el-select v-model="consultation.peopleType" placeholder="请选择" style="width: 100%">
                <el-option
                    label="个人预约"
                    value="个人预约"
                />
                <el-option
                    label="团体预约"
                    value="团体预约"
                />
            </el-select>
            <p style='font-size:14px;margin: 15px 0'>咨询方式:</p>
            <el-select v-model="consultation.mode" placeholder="请选择" style="width: 100%">
                <el-option
                    label="线下咨询"
                    value="线下咨询"
                />
                <el-option
                    label="电话咨询"
                    value="电话咨询"
                    disabled
                />
                <el-option
                    label="网络咨询"
                    value="网络咨询"
                    disabled
                />

            </el-select>
        </div>
        <template #footer>
            <div class="dialog-footer" style='text-align: center'>
                <el-button type="primary" @click="saveAppoint">
                    确定
                </el-button>
            </div>
        </template>
    </el-dialog>
</template>

<style lang='scss'>
.dateMain {
    width: 100%;
    height: 100%;
    padding: 35px 20px;
}

.dateContent {
    display: flex;
    //flex-wrap: wrap;
    overflow-x: auto;
    white-space: nowrap
}

.calendar {
    width: 690px;
    float: left;
    display: inline-block
}

.scheduling {
    width: 690px;
    margin-left: 40px;
    float: left;
    display: inline-block
}

.scheduling-header {
    height: 50.2px;
    padding: 12px 20px;
    border-bottom: 1px solid #dfe6ec;

    el-icon {
        margin: 5px;
    }
}

.scheduling-body {
    width: 100%;
    box-sizing: border-box;
    padding: 12px 20px;
}

.orderBtn {
    padding: 0 30px;
}

.tag {
    width: 156px;
    height: 80px;
    line-height: 80px;
    text-align: center;
    margin: 10px 5px;
    font-size: 16px;
    border-radius: 4px;
    position: relative;
    cursor: pointer;

    .smallTag {
        width: 35px;
        height: 20px;
        line-height: 20px;
        border-radius: 4px;
        text-align: center;
        position: absolute;
        top: 5px;
        right: 5px;
        font-size: 12px;
        color: #fff;
    }

    .smallGreenTag {
        background-color: #13ce66;
        border-color: #13ce66;
    }

    .smallOrangeTag {
        background-color: #ffba00;
        border-color: #ffba00;
    }

    .smallRedTag {
        background-color: #FF4949;
        color: #fff;
    }
}

.tagGreen {
    background-color: rgba(146, 255, 122, .2);
}

.tagOrange {
    background-color: rgba(219, 162, 0, .23);
}

.tagGrey {
    background-color: rgb(230, 230, 230);
}

.tagRed {
    background-color: #FFE8E8;
}

.haveTime,
.noTime {
    width: 100%;
    height: 100%;
    display: flex;
    flex-direction: column;
}

.el-calendar-day {
    padding: 0 !important;
}

.haveTime {
    background-color: #f1ffee;
    //color: #23a500;
}

.haveTime::after {
    content: '可约';
    color: #23a500;
    text-align: center;
    margin-top: 13px;
}

.noTime {
    background-color: rgba(255, 27, 27, .1);
    //color: #ff1b1b;
}

.noTime::after {
    content: '不可约';
    color: #ff1b1b;
    text-align: center;
    margin-top: 13px;
}

.el-dialog__header {
    background-color: #1892ff;
    margin-right: 0;

    .el-dialog__title {
        font-size: 16px;
        color: #fff;
    }

    .el-dialog__headerbtn .el-dialog__close {
        color: #fff !important;
    }
}

.stuTable {
    //background-color: #fafafa;
    padding: 10px;
    border: 1px solid #e6ebf5;
    border-bottom: 0;
    margin-bottom: 0;

    td, th {
        height: 20px;
        line-height: 20px;
        padding: 10px;
        border: 1px solid #e6ebf5;
    }

    th {
        text-align: left !important;
        background-color: #fafafa;
    }
}

.grey {
    width: 185px;
    background-color: #fafafa;
    color: #909399;
    font-size: 14px;
}

.content {
    font-size: 14px;
    color: #606266;
    background-color: #fff;
}

.contextMenu {
    position: fixed;
    top: 0;
    left: 0;

    transform: translate(var(--x), var(--y));

    text-align: center;
    width: 110px;
    height: auto;
    z-index: 99999;
    background-color: #fff;
    overflow: hidden;
    border-radius: 8px;
    border: 1px solid #e6ebf5;
    box-shadow: 0 2px 12px 0 rgba(0,0,0,.1);
    padding: 15px 0;
    font-size: 14px;
    color: #666;
    div:hover {
        color: #409EFF;
        background-color: #D3E3FD;
        cursor: pointer;
    }
}
</style>
